package wjh.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import wjh.pojo.Admin;
import wjh.service.AdminInfoService;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@Controller
@RequestMapping("/loginController")
public class Login_adminController {

    @Autowired
    private AdminInfoService adminInfoService;

    @RequestMapping("/loginAdmin")
    public String handleLogin(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              @RequestParam("captcha") String captcha,
                              HttpSession session, HttpServletRequest request, Model model) {
        Admin admin = adminInfoService.findAdminLogin(username,password);
        String correctCaptcha = (String) session.getAttribute("captcha");
        if (admin!=null){
            if (correctCaptcha != null && correctCaptcha.equals(captcha)) {
                Admin admin1 = adminInfoService.findId(username,password);
                int id=admin1.getId();
                model.addAttribute("id",id);
                model.addAttribute("admin",admin);

                HttpSession session1 = request.getSession();
                session1.setAttribute("isLoggedIn", true);

                return "forward:/jsp/adminIndex.jsp";
            } else {
                model.addAttribute("message", "验证码错误！");
                return "login_admin";
            }
        }else {
            model.addAttribute("message", "用户名密码错误！");
            return "login_admin";
        }
    }
    @RequestMapping("/register")
    public String handleLogins(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              @RequestParam("captcha") String captcha,
                              HttpSession session, HttpServletRequest request, Model model) {
        Admin admin = adminInfoService.findAdminRegister(username);
        String correctCaptcha = (String) session.getAttribute("captcha");
        if (admin==null){
            if (correctCaptcha != null && correctCaptcha.equals(captcha)) {
                adminInfoService.register(username,password);
                HttpSession session1 = request.getSession();
                session1.setAttribute("isLoggedIn", true);
                return "login_admin";
            } else {
                model.addAttribute("message", "验证码错误！");
                return "register_admin";
            }
        }else {
            model.addAttribute("message", "用户名已存在，请重新注册！");
            return "register_admin";
        }
    }

    @RequestMapping("/captcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        response.setContentType("image/png");
        BufferedImage bufferedImage = new BufferedImage(150, 50, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();

        g2d.setColor(Color.LIGHT_GRAY);
        g2d.fillRect(0, 0, 150, 50);

        String captchaCode = generateRandomString(5);
        session.setAttribute("captcha", captchaCode);

        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font("Arial", Font.BOLD, 30));
        g2d.drawString(captchaCode, 20, 35);

        g2d.dispose();
        OutputStream os = response.getOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        os.flush();
    }

    private String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            captcha.append(characters.charAt(index));
        }
        return captcha.toString();
    }
}
